import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import {postRequest} from "./utils/api";
import {putRequest} from "./utils/api";
import {getRequest} from "./utils/api";
import {deleteRequest} from "./utils/api";
import axios from "axios";



Vue.config.productionTip = false
Vue.use(ElementUI);

Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.getRequest = getRequest;
Vue.prototype.deleteRequest = deleteRequest;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

router.beforeEach((to, from, next) => {
  console.log('上一个页面：', from)
  console.log('下一个页面：', to)
  console.log(sessionStorage.getItem('userInfo'))
  let userToken = localStorage.getItem('token')
  let role = JSON.parse(sessionStorage.getItem('userInfo')).role;
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (userToken) { // 判断本地是否存在token
      if (to.meta.roles.length !== 0) {
        for (let i = 0; i < to.meta.roles.length; i++) {
          if (role === to.meta.roles[i]) {
            next()
            break
          } else if (i === to.meta.roles.length - 1) {
            next({
              path: '/Error'
            })
          }
        }
      } else {
        next()
      }
    } else {
      next({
        path: '/Login'
      })
    }
  } else {
    next()
  }
  /* 如果本地存在token,则不允许直接跳转到登录页面 */
  if (to.fullPath === '/Login') {
    if (userToken) {
      next({
        path: from.fullPath
      })
    } else {
      next()
    }
  }
})
axios.interceptors.request.use(config=> {
  if (localStorage.getItem('token')) {
    config.headers.Authorization = `${localStorage.getItem('token')}`;
  }
  return config;
},error => {
  return Promise.reject(error);
})